package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssm.sport.mapper.CartMapper;
import com.ssm.sport.entity.Cart;
import com.ssm.sport.entity.Product;
import com.ssm.sport.service.CartService;
import com.ssm.sport.service.ProductService;
import com.ssm.sport.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务实现类
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private ProductService productService;

    @Override
    public List<Map<String, Object>> getCartList(Integer userId) {
        return baseMapper.selectCartWithProductByUserId(userId);
    }

    @Override
    public List<CartVO> getCartVOList(Integer userId) {
        List<Map<String, Object>> cartMapList = getCartList(userId);
        List<CartVO> cartVOList = new ArrayList<>();
        
        for (Map<String, Object> map : cartMapList) {
            CartVO cartVO = new CartVO();
            cartVO.setId((Integer) map.get("id"));
            cartVO.setUserId((Integer) map.get("user_id"));
            cartVO.setProductId((Integer) map.get("product_id"));
            cartVO.setQuantity((Integer) map.get("quantity"));
            cartVO.setChecked((Integer) map.get("checked"));
            cartVO.setProductName((String) map.get("productName"));
            cartVO.setProductPrice((BigDecimal) map.get("productPrice"));
            cartVO.setProductImage((String) map.get("productImage"));
            
            // 计算商品总价
            BigDecimal productTotalPrice = cartVO.getProductPrice().multiply(new BigDecimal(cartVO.getQuantity()));
            cartVO.setProductTotalPrice(productTotalPrice);
            
            cartVOList.add(cartVO);
        }
        
        return cartVOList;
    }

    @Override
    public List<CartVO> getCheckedCartItems(Integer userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("checked", 1);
        List<Cart> cartList = baseMapper.selectList(queryWrapper);
        return assembleCartVOList(cartList);
    }

    @Override
    @Transactional
    public void clearCart(Integer userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        baseMapper.delete(queryWrapper);
    }

    @Override
    public int updateCheckedByUserId(Integer userId, Integer checked) {
        return baseMapper.updateCheckedByUserId(userId, checked);
    }

    @Override
    public Map<String, Object> showCart(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取购物车列表
        List<Map<String, Object>> cartList = getCartList(userId);
        
        // 计算总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Map<String, Object> cart : cartList) {
            // 判断是否选中
            Integer checked = (Integer) cart.get("checked");
            if (checked == 1) {
                BigDecimal price = (BigDecimal) cart.get("productPrice");
                Integer quantity = (Integer) cart.get("quantity");
                
                // 添加到总价中
                totalPrice = totalPrice.add(price.multiply(new BigDecimal(quantity)));
            }
        }
        
        result.put("cartList", cartList);
        result.put("totalPrice", totalPrice);
        
        return result;
    }

    @Override
    @Transactional
    public int addToCart(Integer userId, Integer productId, Integer count) {
        // 检查购物车中是否已存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);
        Cart existCart = getOne(queryWrapper);

        if (existCart != null) {
            // 已存在，更新数量
            existCart.setQuantity(existCart.getQuantity() + count);
            return updateById(existCart) ? 1 : 0;
        } else {
            // 不存在，新增购物车项
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(count);
            cart.setChecked(1); // 默认选中
            return save(cart) ? 1 : 0;
        }
    }

    @Override
    public int deleteFromCart(Integer userId, Integer productId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);
        return baseMapper.delete(queryWrapper);
    }

    @Override
    public int selectProduct(Integer userId, Integer productId, Integer checked) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                    .eq("product_id", productId)
                    .set("checked", checked);
        return baseMapper.update(null, updateWrapper);
    }

    @Override
    public int selectAllProducts(Integer userId, Integer checked) {
        return updateCheckedByUserId(userId, checked);
    }

    @Override
    @Transactional
    public int updateCart(Integer userId, Integer productId, Integer count) {
        // 检查购物车中是否已存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);
        Cart cart = getOne(queryWrapper);
        
        if (cart != null) {
            // 更新数量
            cart.setQuantity(count);
            return updateById(cart) ? 1 : 0;
        }
        
        return 0;
    }

    private List<CartVO> assembleCartVOList(List<Cart> cartList) {
        List<CartVO> cartVOList = new ArrayList<>();
        
        for (Cart cartItem : cartList) {
            Product product = productService.getById(cartItem.getProductId());
            if (product != null) {
                CartVO cartVO = new CartVO();
                cartVO.setId(cartItem.getId());
                cartVO.setUserId(cartItem.getUserId());
                cartVO.setProductId(cartItem.getProductId());
                cartVO.setQuantity(cartItem.getQuantity());
                cartVO.setProductName(product.getName());
                cartVO.setProductImage(product.getMainImage());
                cartVO.setProductPrice(product.getPrice());
                cartVO.setChecked(cartItem.getChecked());
                
                // 计算商品总价
                if (product.getPrice() != null) {
                    cartVO.setProductTotalPrice(product.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
                }
                
                cartVOList.add(cartVO);
            }
        }
        
        return cartVOList;
    }
} 